package com.ljf.interestingmaps.maps;

import android.Manifest;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.ljf.interestingmaps.R;
import com.ljf.interestingmaps.util.PermissionUtils;

public class MapsActivity extends AppCompatActivity implements View.OnClickListener, OnMapReadyCallback, GoogleMap.OnMyLocationClickListener, ActivityCompat.OnRequestPermissionsResultCallback {

    private GoogleMap mMap;

    private ImageView ivMenu;
    private LinearLayout lltMenu;
    private LinearLayout lltMenuSatellite, lltMenuFlatten, lltMenuEyeView;
    /**
     * Request code for location permission request.
     *
     * @see #onRequestPermissionsResult(int, String[], int[])
     */
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;

    /**
     * Flag indicating whether a requested permission has been denied after returning in
     * {@link #onRequestPermissionsResult(int, String[], int[])}.
     */
    private boolean mPermissionDenied = false;

    private LatLng currentLocation = new LatLng(-33.87365, 151.20689);


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        enableMyLocation();
        mapFragment.getMapAsync(this);

        initView();
    }

    private void initView() {
        ivMenu = findViewById(R.id.act_map_menu_iv);
        lltMenuSatellite = findViewById(R.id.act_map_menu_satellite);
        lltMenuFlatten = findViewById(R.id.act_map_menu_flatten);
        lltMenuEyeView = findViewById(R.id.act_map_menu_eye_view);
        lltMenu = findViewById(R.id.act_map_menu);

        ivMenu.setOnClickListener(this);
        lltMenuSatellite.setOnClickListener(this);
        lltMenuFlatten.setOnClickListener(this);
        lltMenuEyeView.setOnClickListener(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney, Australia, and move the camera.
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            enableMyLocation();
            return;
        }
        mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                closeMenu();
            }
        });
        mMap.setMyLocationEnabled(true);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 16));

        mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
            @Override
            public void onMyLocationChange(Location location) {

                currentLocation = new LatLng(location.getLatitude(), location.getLongitude());

                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 16));

                mMap.setOnMyLocationChangeListener(null);
            }
        });
    }

    /**
     * Enables the My Location layer if the fine location permission has been granted.
     */
    private void enableMyLocation() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            // Permission to access the location is missing.
            PermissionUtils.requestPermission(MapsActivity.this, LOCATION_PERMISSION_REQUEST_CODE,
                    Manifest.permission.ACCESS_FINE_LOCATION, true);
        } else if (mMap != null) {
            // Access to the location has been granted to the app.
            mMap.setMyLocationEnabled(true);
        }

    }
    @Override
    public void onMyLocationClick(@NonNull Location location) {
        if(location!=null)
        {
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 17));
        }

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
            return;
        }

        if (PermissionUtils.isPermissionGranted(permissions, grantResults,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            // Enable the my location layer if the permission has been granted.
            enableMyLocation();
        } else {
            // Display the missing permission error dialog when the fragments resume.
            mPermissionDenied = true;
        }
    }


    @Override
    protected void onResumeFragments() {
        super.onResumeFragments();
        if (mPermissionDenied) {
            // Permission was not granted, display error dialog.
            showMissingPermissionError();
            mPermissionDenied = false;
        }
    }

    /**
     * Displays a dialog with error message explaining that the location permission is missing.
     */
    private void showMissingPermissionError() {
        PermissionUtils.PermissionDeniedDialog
                .newInstance(true).show(getSupportFragmentManager(), "dialog");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.act_map_menu_iv:
                openMenu();
                break;
            case R.id.act_map_menu_satellite:
                if (mMap != null) {
                    mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
                    lltMenuSatellite.setBackgroundResource(R.drawable.shape_map_menu_item);
                    lltMenuFlatten.setBackgroundColor(Color.parseColor("#00000000"));
                    lltMenuEyeView.setBackgroundColor(Color.parseColor("#00000000"));
                    closeMenu();
                }
                break;
            case R.id.act_map_menu_flatten:
                if (mMap != null) {
                    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                    lltMenuSatellite.setBackgroundColor(Color.parseColor("#00000000"));
                    lltMenuFlatten.setBackgroundResource(R.drawable.shape_map_menu_item);
                    lltMenuEyeView.setBackgroundColor(Color.parseColor("#00000000"));
                    closeMenu();
                }
                break;
            case R.id.act_map_menu_eye_view:
                if (mMap != null) {
                    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
                    lltMenuSatellite.setBackgroundColor(Color.parseColor("#00000000"));
                    lltMenuFlatten.setBackgroundColor(Color.parseColor("#00000000"));
                    lltMenuEyeView.setBackgroundResource(R.drawable.shape_map_menu_item);
                    closeMenu();
                }
                break;
        }
    }

    private void openMenu() {
        lltMenu.setVisibility(View.VISIBLE);
        Animation animation = AnimationUtils.loadAnimation(this, R.anim.menu_right_translate_in);
        LayoutAnimationController inController = new LayoutAnimationController(animation);
        lltMenu.setLayoutAnimation(inController);
        lltMenu.startAnimation(animation);
        lltMenu.startLayoutAnimation();
    }

    private void closeMenu() {
        if (lltMenu.getVisibility() == View.VISIBLE) {
            lltMenu.setVisibility(View.GONE);
            Animation animation = AnimationUtils.loadAnimation(this, R.anim.menu_right_translate_out);
            LayoutAnimationController outController = new LayoutAnimationController(animation);
            lltMenu.setLayoutAnimation(outController);
            lltMenu.startAnimation(animation);
            lltMenu.startLayoutAnimation();
        }
    }

}